<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
     
    

      <el-form-item label="时间范围" prop="timeRange">
        <el-select v-model="queryParams.timeRange" placeholder="请选择时间范围" clearable @change="handleTimeRangeChange">
          <el-option label="当日" value="today" />
          <el-option label="当月" value="month" />
          <el-option label="自定义" value="custom" />
        </el-select>
      </el-form-item>
      <el-form-item label="日期范围" prop="dateRange" v-if="queryParams.timeRange === 'custom'">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleDateRangeChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['emotion:records:add']"
        >新增</el-button>
      </el-col>
      <!--
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleShowDetails"
          v-hasPermi="['emotion:records:edit']"
        >修改</el-button>
      </el-col>
      -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['emotion:records:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['emotion:records:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 卡片展示 -->
    <!-- <el-row :gutter="20" class="record-grid">
      <el-col :span="12" v-for="(record, index) in recordsList" :key="record.emotionId" class="record-item">
        <el-card class="record-card">
          <div class="record-content">
            <div class="record-info">
              <div class="record-header">
                <span class="record-index">#{{ index + 1 }}</span>
                <span class="record-username">{{ record.userName }}</span>
              </div>
              <div class="record-details">
                <p><strong>检测时间：</strong>{{ parseTime(record.timestamp, '{y}-{m}-{d} {h}:{i}:{s}') }}</p>
                <p><strong>创建时间：</strong>{{ parseTime(record.createdAt, '{y}-{m}-{d}') }}</p>
              </div>
            </div>
            <div class="record-chart">
              <div ref="chartRefs" :id="'chart-' + record.emotionId" style="width: 100%; height: 200px;"></div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row> -->
   
    
    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="recordsList" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" align="center" />
        
         <el-table-column label="情绪检测结果" align="center" prop="emotionPercentage">
            <template #default="scope">
               <span>{{ findLargestPersentage(scope.row.emotionPercentage) }}</span>
            </template>
         </el-table-column>
         <el-table-column label="所属部门" prop="deptName" :show-overflow-tooltip="true" width="300" align="center"/>
         <el-table-column label="创建时间" align="center" prop="createdAt">
            <template #default="scope">
               <span>{{ parseTime(scope.row.createdAt) }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <!--
              <el-tooltip content="修改" placement="top" v-if="scope.row.roleId !== 1">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:role:edit']"></el-button>
              </el-tooltip>
              -->
              <el-tooltip content="查看详情" placement="top" v-if="scope.row.roleId !== 1">
                <el-button link type="primary" icon="link" @click="handleShowDetails(scope.row)" v-hasPermi="['system:role:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" v-if="scope.row.roleId !== 1">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:role:remove']"></el-button>
              </el-tooltip>
            </template>
         </el-table-column>
      </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改情绪检测记录对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="recordsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联用户ID" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入关联用户名" />
        </el-form-item>
        <el-form-item label="关联部门名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入关联部门名" />
        </el-form-item>
        <el-form-item label="检测时间戳" prop="timestamp">
          <el-input v-model="form.timestamp" placeholder="请输入检测时间戳" />
        </el-form-item>
        <el-form-item label="各情绪百分比" prop="emotionPercentage">
          <el-input v-model="form.emotionPercentage" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 情绪检测记录详情对话框 -->
    <el-dialog :title="title" v-model="detailOpen" width="800px" append-to-body>
      <el-row :gutter="20">
        <!-- 左侧信息 -->
        <el-col :span="12">
          <el-card>
            <el-row :span="12" :gutter="20">
              <el-col :span="8">
                <el-card>
                  <div class="detection-result">
                    <div class="result-icon">
                      <img src="" alt="检测结果" style="width: 100px; height: 100px;">
                    </div>
                    <div class="result-text">检测结果</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="16">
                <el-card>
                  <div id="detail-bar-chart" style="width: 100%; height: 180px;"></div>
                </el-card>
              </el-col>
            </el-row>
            <el-row :span="12" style="width: 100%;margin-top: 20px;">
              <el-col :span="24">
                <el-card style="background-color: rgb(209.4, 236.7, 195.9);padding: 10px;">
                  <h4>针对当前情绪的建议</h4>
                  <ul class="suggestion-list">
                    <li>保持积极的心态，与他人分享您的快乐</li>
                    <li>记录下此刻的心情，日后可以回顾</li>
                    <li>做一件让自己更开心的小事</li>
                  </ul>
                </el-card>
              </el-col>
            </el-row>
            <template #footer>
              <h6 class="analysis-footer">
                检测时间：{{ parseTime(form.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}
              </h6>
            </template>
          </el-card>
        </el-col>

        <!-- 右侧信息 -->
        <el-col :span="12">
          <el-card>
            <el-descriptions column="1" border>
              <el-descriptions-item label="记录编号">{{ form.emotionId }}</el-descriptions-item>
              <el-descriptions-item label="用户名称">{{ form.userName }}</el-descriptions-item>
              <el-descriptions-item label="所属部门">{{ form.deptName }}</el-descriptions-item>
              <el-descriptions-item label="情绪识别结果">{{ findLargestPersentage(form.emotionPercentage) }}</el-descriptions-item>
            </el-descriptions>

            <div class="record-chart">
              <div ref="chartRefs" :id="'chart-' + form.emotionId" style="width: 100%; height: 200px;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancel">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Records">
import { listRecords, getRecords, delRecords, addRecords, updateRecords } from "@/api/emotion/records"
import * as echarts from 'echarts'
import { valueEquals } from "element-plus"

const { proxy } = getCurrentInstance()

const recordsList = ref([])
const open = ref(false)
const detailOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const chartRefs = ref([])
const dateRange = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 4, // 修改为每页显示4条记录
    userName: null,
    deptName: null,
    timeRange: 'month', // 默认选择当月
    beginTime: null,
    endTime: null,
  },
  rules: {
    userId: [
      { required: true, message: "关联用户ID不能为空", trigger: "blur" }
    ],
    timestamp: [
      { required: true, message: "检测时间戳不能为空", trigger: "blur" }
    ],
    emotionPercentage: [
      { required: true, message: "各情绪百分比不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// 初始化时间范围
onMounted(() => {
  handleTimeRangeChange('month')
})

// 处理时间范围变更
function handleTimeRangeChange(value) {
  if (value === 'today') {
    // 设置为当天
    const today = new Date()
    const formattedDate = formatDate(today)
    queryParams.value.beginTime = formattedDate
    queryParams.value.endTime = formattedDate
    dateRange.value = [formattedDate, formattedDate]
  } else if (value === 'month') {
    // 设置为当月
    const today = new Date()
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1)
    const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0)
    
    queryParams.value.beginTime = formatDate(firstDay)
    queryParams.value.endTime = formatDate(lastDay)
    dateRange.value = [formatDate(firstDay), formatDate(lastDay)]
  } else if (value === 'custom') {
    // 自定义时间范围，不做处理，等待用户选择
    if (!dateRange.value || dateRange.value.length === 0) {
      dateRange.value = []
      queryParams.value.beginTime = null
      queryParams.value.endTime = null
    }
  } else {
    // 清除时间范围
    dateRange.value = []
    queryParams.value.beginTime = null
    queryParams.value.endTime = null
  }
}

// 处理日期范围变更
function handleDateRangeChange(value) {
  if (value && value.length === 2) {
    queryParams.value.beginTime = value[0]
    queryParams.value.endTime = value[1]
  } else {
    queryParams.value.beginTime = null
    queryParams.value.endTime = null
  }
}

// 格式化日期为 YYYY-MM-DD
function formatDate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 解析情绪百分比数据
function parseEmotionData(emotionPercentage) {
  const emotions = emotionPercentage.split(', ')
  return emotions.map(emotion => {
    const [name, value] = emotion.split(':')
    return {
      name: name,
      value: parseFloat(value)
    }
  })
}

// 找到百分比最大的情绪
function findLargestPersentage(emotionPercentage) {
  const emotions = emotionPercentage.split(',')
  var maxValue = -Infinity
  var largestEmotion = ""
  emotions.forEach(emotion => {
    const [name, value] = emotion.split(':')
    if(value > maxValue){
      maxValue = parseFloat(value)
      largestEmotion = name
    }
  });
  return largestEmotion
}

// 初始化图表
function initChart(record) {
  const chartDom = document.getElementById('chart-' + record.emotionId)
  if (!chartDom) return

  const myChart = echarts.init(chartDom)
  const emotionData = parseEmotionData(record.emotionPercentage)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}%'
    },
    series: [
      {
        name: '情绪分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}%'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: emotionData
      }
    ]
  }

  myChart.setOption(option)
}

/** 查询情绪检测记录列表 */
function getList() {
  loading.value = true
  listRecords(queryParams.value).then(response => {
    recordsList.value = response.rows
    total.value = response.total
    loading.value = false
    
    // 在数据加载完成后初始化图表
    nextTick(() => {
      recordsList.value.forEach(record => {
        initChart(record)
      })
    })
  })
}

// 取消按钮
function cancel() {
  open.value = false
  detailOpen.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    emotionId: null,
    userId: null,
    userName:null,
    deptName:null,
    timestamp: null,
    emotionPercentage: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm("recordsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  queryParams.value.timeRange = 'month' // 重置为默认当月
  handleTimeRangeChange('month')
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.emotionId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加情绪检测记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _emotionId = row.emotionId || ids.value
  getRecords(_emotionId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改情绪检测记录"
  })
}

// 渲染详情页柱状图
function renderDetailBarChart(record) {
  nextTick(() => {
    const chartDom = document.getElementById('detail-bar-chart')
    if (!chartDom) return
    const myChart = echarts.init(chartDom)
    const emotionData = parseEmotionData(record.emotionPercentage)
    
    myChart.setOption({
      xAxis: {
        type: "value",
        axisTick: { show: true },
        axisLine: {
          show: true,
        },
      },
      yAxis: {
        type: "category",
        data: emotionData.map(item => item.name),
      },
      grid: { left: '1%', right: '1%', top: '2%', bottom: 0, containLabel: true },
      series: [{
        name: '情绪组成',
        type: 'bar',
        avoidLabelOverlap: false,
        label: { show: false },
        data: emotionData
      }]
    })
  })
}

/** 展示详情按钮操作*/
function handleShowDetails(row) {
  reset()
  const _emotionId = row.emotionId || ids.value
  getRecords(_emotionId).then(response => {
    form.value = response.data
    detailOpen.value = true
    title.value = "情绪记录详情"
    
    // 在数据加载完成后初始化图表
    nextTick(() => {
      initChart(form.value)
      renderDetailBarChart(form.value)
    })
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordsRef"].validate(valid => {
    if (valid) {
      if (form.value.emotionId != null) {
        updateRecords(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRecords(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _emotionIds = row.emotionId || ids.value
  proxy.$modal.confirm('是否确认删除情绪检测记录编号为"' + _emotionIds + '"的数据项？').then(function() {
    return delRecords(_emotionIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('emotion/records/export', {
    ...queryParams.value
  }, `records_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.record-grid {
  margin-top: 20px;
}

.record-item {
  margin-bottom: 20px;
}

.record-card {
  height: 100%;
}

.record-content {
  display: flex;
  height: 100%;
}

.record-info {
  flex: 1;
  padding-right: 20px;
}

.record-chart {
  flex: 1;
}

.record-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.record-index {
  font-size: 18px;
  font-weight: bold;
  margin-right: 10px;
}

.record-username {
  font-size: 16px;
  font-weight: bold;
}

.record-details {
  font-size: 14px;
  color: #666;
}

.record-details p {
  margin: 5px 0;
}
.detection-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.result-icon {
  margin-bottom: 10px;
}

.result-text {
  font-size: 16px;
  font-weight: bold;
  text-align: center;
}

.suggestion-list {
  padding-left: 20px;
  margin: 10px 0;
}

.suggestion-list li {
  margin-bottom: 8px;
  color: #333;
}

.analysis-footer {
  text-align: center;
  margin: 0;
  padding: 0;
  color: #666;
  font-size: 12px;
}
</style>
